import { BaseInjectHandler } from "../BaseInjectHandler";
import { EMessageC2C } from "../../../common/EMessageC2C";
import { TransPack } from "../../../server/framework/common/TransPack";
import { ObjData } from "../common/ObjData";
import { EDefineObjType } from "../common/EDefineObjType";
import { NodeTypeHelper } from "../action/NodeTypeHelper";
import { NodeDetailHelper } from "../action/NodeDetailHelper";

const ID_STR = '$__debuggerid__';

/**
 * 处理hierachy列表查询
 */
export class HandleQueryObjList extends BaseInjectHandler {

    msgId: number = EMessageC2C.QueryObjList;

    private _cacheId: number;

    private _cacheNodeMap: Map<number, Laya.Node>;

    private _lastJson: string;

    _OnInit() {
        this._cacheId = 1;
        this._cacheNodeMap = new Map<number, Laya.Node>();
    }

    _OnHandleMsg(msg: TransPack) {
        let isForce = msg.data.isForce as boolean;

        let rootNode = new ObjData();
        this._SearchChild(Laya.stage, rootNode);
        let newJson = JSON.stringify(rootNode);
        if (this._lastJson == newJson && !isForce) {
            this.owner.SendTransOtherData(EMessageC2C.QueryObjList_Back, null);
        } else {
            this.owner.SendTransOtherData(EMessageC2C.QueryObjList_Back, rootNode);
        }
        this._lastJson = newJson;
    }

    private _SearchChild(node: Laya.Node, matchNode: ObjData) {
        let debuggerId = node[ID_STR];
        if (debuggerId == null) {
            debuggerId = this._cacheId++;
            node[ID_STR] = debuggerId;
            this._cacheNodeMap.set(debuggerId, node);
        }
        matchNode.i = debuggerId;
        matchNode.n = node.name;
        this._SetActive(node, matchNode);
        this._SetType(node, matchNode);

        for (let i = 0; i < node.numChildren; ++i) {
            let getChild = node.getChildAt(i);
            let newNode = new ObjData();
            this._SearchChild(getChild, newNode);
            matchNode.c.push(newNode);
        }
    }

    private _SetType(node: Laya.Node, matchNode: ObjData) {
        matchNode.t = NodeTypeHelper.GetNodeType(node);
    }

    private _SetActive(node: Laya.Node, matchNode: ObjData) {
        matchNode.a = NodeDetailHelper.GetNodeActive(node);
    }

    public GetNodeById(id: number): Laya.Node {
        return this._cacheNodeMap.get(id);
    }

    public RemoveNodeById(id: number) {
        this._cacheNodeMap.delete(id);
    }

}